#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "wxt520.h"
char proc_buff[100];
char recv_buff[256];
/*最近一次响应字符串*/
struct recv_data
{
	char xu[64];/*通讯响应字符串*/
	char wu[64];/*风传感器响应字符串*/
	char tu[64];/*温度传感器*/
	char ru[64];/*降水传感器*/
	char su[64];/*监控方*/
	
	char r1[64];/*风数据*/
	char r2[64];/*温度数据*/
	char r3[64];/*降水数据*/
	char r5[64];/*监控方数据*/
	
	char r0[64];/*合成数据*/
	
};

extern int open_serial(const char *serial_port);
int main(int argc,char **argv)
{
	int fd = 0;
	int err = 0;
	int n = 0;
	char cmd[64];
	fd_set rfd;
	struct __XU xu;
	struct timeval timeout;
	timeout.tv_sec = 5;
	timeout.tv_usec = 0;
	if (getuid())
	{
		printf("this program must be run in root\n");
		return -1;
	}
	fd = open_serial("/dev/ttyUSB0");
	if (fd < 0)
	{
		printf("open serial error\n");
		return -1;
	}

	for (;;)
	{
		FD_ZERO(&rfd);
		FD_SET(fd, &rfd);
		err = -1;
		sleep(2);
		err = select(fd + 1, &rfd, NULL, NULL, &timeout);
		switch (err)
		{
			case -1:
				perror("select");
				break;
			default:
			{
				if (FD_ISSET(fd,&rfd))
				{
					memset(proc_buff,0,512);
					write(fd,"0XU\015\012",strlen("0XU\015\012"));
					n = read(fd,proc_buff,512);
					//index(proc_buff,'\n');
					sscanf(proc_buff,G_XU,P_XU(xu));
					//printf("str:%s\n",proc_buff);
					xu_display(xu);
				}
			}
		}
	}
	close(fd);
	return 0;
}

void xu_display(struct __XU xu)
{
	char tmp[32];
	switch (xu._M)
	{
		case 'A':
			sprintf(tmp,"ASCII,自动");
			break;
		case 'a':
			sprintf(tmp,"ASCII,自动且包含 CRC");
			break;
		case 'P':
			sprintf(tmp,"ASCII,轮询");
			break;
		case 'p':
			sprintf(tmp,"ASCII,轮询,包含 CRC");
			break;
		case 'N':
			sprintf(tmp,"NMEA 0183 v3.0,自动");
			break;
		case 'Q':
			sprintf(tmp,"NMEA 0183 v3.0,查询(= 轮询)");
			break;
		case 'S':
			sprintf(tmp,"SDI-12 v1.3");
			break;
		case 'R':
			sprintf(tmp,"SDI-12 v1.3 连续测量");
			break;
	}
	printf("\t\t\t收到通讯报文\n");
	printf("设备地址\t\t:%d\n",xu._A);
	printf("通信协议\t\t:%s\n",tmp);
	printf("串行接口\t\t:%s\n",(xu._C == 3)?"RS485":"others");
	printf("合成数据时间间隔\t:%d\n",xu._I);
	printf("波特率\t\t\t:%d\n",xu._B);
	printf("数据位\t\t\t:%d\n",xu._D);
	printf("奇偶性\t\t\t:%c\n",xu._P);
	printf("停止位\t\t\t:%d\n",xu._S);
	printf("线延迟\t\t\t:%d\n",xu._L);
	printf("设备名称\t\t:%s\n",xu._N);
	printf("软件版本\t\t:%s\n",xu._V);
}